package com.ganbing518.commons.utils;

import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyStore;
import java.util.Optional;


public class SslUtils {

    private static final PoolingHttpClientConnectionManager CONNECT_MANAGER;
    private static final CloseableHttpClient HTTP_CLIENT;
    private static SSLConnectionSocketFactory sslSocketFactory = null;

    static {

        try {
            String caPkcs8Pass = "123456";
            KeyStore keyStore = CertPemReader.loadKeyStore(Constant.ca, Constant.pk, Optional.of(caPkcs8Pass));
            KeyStore trustStore = CertPemReader.loadTrustStore(Constant.puk);

            SSLContext sslcontext = SSLContexts.custom()
                    .loadKeyMaterial(keyStore, caPkcs8Pass.toCharArray())
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
                    .build();
            HostnameVerifier allowAllHostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            sslSocketFactory = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"}, null, allowAllHostnameVerifier);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build();
        CONNECT_MANAGER = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        int maxRoute = 50;
        int connectTimeout = 24000;
        int readTimeout = 5000;
        CONNECT_MANAGER.setDefaultMaxPerRoute(maxRoute);
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout).setConnectTimeout(connectTimeout)
                .setSocketTimeout(readTimeout)
                .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
        HTTP_CLIENT = HttpClients.custom().setConnectionManager(CONNECT_MANAGER).setDefaultRequestConfig(requestConfig).build();
    }


    public static CloseableHttpClient getHttpClient() {
        return HTTP_CLIENT;
    }
}